package com.kwin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class ZipServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉浏览器获取的是压缩数据
        resp.setHeader("Content-Encoding", "gzip");

        String str = "fhksfhskjfhskjfhskjdfhsfsdfsfasfhnakjshgvksafhksbnskvbskjvgskbvcskgfkgpjffskjhfskfbaskfbkjsaf" +
                     "sfhskfhsajkfbaiuuiebfwkjfbnwkfjwalfnmalwfnwjlfwauhiuwrnwlfknwjkkwbfkwjbfwkfbkwjbrkjwfnwkfkwnf";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(str.getBytes());
        gzipOutputStream.close();

        byte[] bytes = byteArrayOutputStream.toByteArray();
        System.out.println("原来的长度是：" + str.length());
        System.out.println("压缩后的长度是：" + bytes.length);
        resp.getOutputStream().write(bytes);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
